import { Button, message, Modal ,Input} from 'antd';
import React, { useState, useRef, useEffect,useContext } from 'react';
import ProTable from '@ant-design/pro-table';
import AddForm from './components/AddForm';
import { addTest, queryList, removeTest, updateTest, getGroupList } from './service';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import { UserContext } from '@/layouts/UserProvider';

const TableList = (props) => {
  const [groupList, setGroupList] = useState();
  const [updateModalVisible, handleDetailModalVisible] = useState(false);
  const [type, setType] = useState('');
  const actionRef = useRef();
  const userCtx = useContext(UserContext);
  const userType=userCtx?.userInfo?.type??'';
  const permits=userCtx.userPermits;
  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    try {
      await addTest({
        type:2,
        name: fields.name,
        group: fields.group,
        phone: fields.phone,
      }).then((data)=>{
        hide();
        if(data.code=='200'){
          message.success('添加成功');
          handleDetailModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }else{
          message.error(data.msg);
        }
      })
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
    }
  };
  /**
   * 编辑
   */
   const handleEdit = async (fields, v) => {
    const hide = message.loading('正在编辑');
    try {
      const res = await updateTest({
        type:2,
        name: fields.name,
        group: fields.group,
        phone: fields.phone,
        id: v.id,
      });
      hide();
      if (res.code == '200') {
        message.success('编辑成功');
        handleDetailModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error('编辑失败请重试！');
      }
    } catch (error) {
      hide();
      message.error('编辑失败请重试！');
    }
  };
  useEffect(() => {
    getGroupList().then((data) => {
      let result = data?.data;
      let list = {};
      if(result && result.length>0){
        result.forEach((item, i) => {
          list[item.group] = { text: item.group, status: item.group };
        });
        setGroupList(list);
      }

    });
  }, []);
  const handleDelTest = (record) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '是否要删除？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        removeTest({ id: record.id }).then((data) => {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        });
      },
    });
  };
  const columns = [
    {
      title: '测试人员姓名',
      dataIndex: 'name',
      renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        if (status === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            // value 和 onchange 会通过 form 自动注入。
            <Input
              // 自定义配置
              placeholder="请输入"
              maxLength={256}
            />
          );
        }
        return defaultRender(_);
      }
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      key: 'phone',
      renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        if (search === 'false') {
          return null;
        }
        const search = form.getFieldValue('search');
        if (search !== 'false') {
          return (
            // value 和 onchange 会通过 form 自动注入。
            <Input
              // 组件的配置
              {...fieldProps}
              // 自定义配置
              placeholder="请输入"
              maxLength={11}
            />
          );
        }
        return defaultRender(_);
      }
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      search: false,
    },

    {
      title: '部门',
      dataIndex: 'group',
      search: false,
     },
    {
      title: '所属部门',
      dataIndex: 'group',
      hideInTable: true,
      hideInForm: true,
      valueEnum: groupList,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let res=[];
        if(permits.includes('detailSysMember')){
          res.push( <Button size="small"
            key="search"
            onClick={() => {
              handleDetailModalVisible(record);
              setType(2);
            }}
          >
            查看
          </Button>);
        }
        if(permits.includes('updateSysMember')){
          res.push( <Button size="small"
            key="edit"
            onClick={() => {
              handleDetailModalVisible(record);
              setType(1);
            }}
          >
            编辑
          </Button>);
        }
        if(permits.includes('deleteSysMember')){
          res.push(<Button size="small" key="detail" onClick={() => handleDelTest(record)}>
            删除
          </Button>)
        }
        return res
      }

    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="key"
        search={{
          collapsed: false,
          defaultCollapsed: false,
          collapseRender: () => '',
          labelWidth: 120,
          searchText: '搜索',
        }}
        request={async (params, sorter, filter) => {
          try{
            params.type = 2;
            params.is_total=true;
            params.limit=params.pageSize;
            params.offset=(params.current-1)*params.pageSize;
            const res = await queryList({ ...params, sorter, filter });
            if (res.data == null && res.total != 0) {
              params.current = params.current - 1;
              params.offset = (params.current - 1) * params.pageSize;
              res = await queryList({ ...params, sorter, filter });
            }
            return {data: JSON.stringify(res.data) != '{}'?res.data:[], success: true, total: res.total || 0}

          }catch(error){
            return { data: [], success: false, total: 0}

          }
        }}
        columns={columns}
        toolBarRender={() =>
        {
          let res = [];
          if (permits.includes('addSysMember')) {
            res.push(<Button
              type="primary"
              key="primary"
              onClick={() => {
                handleDetailModalVisible(true);
                setType(0);
              }}
            >
              添加测试人员
            </Button>)
          }
          return res;
        }
          
         }
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共有 ${total} 条记录`,
          pageSize:10,
        }}
      />
      <AddForm
        onSubmit={async (value) => {
          console.log('&&&&&&&&&&&&&&');
          console.log(value);
          //添加
          if (type == 0) {
            await handleAdd(value);
          }
          //编辑
          if (type == 1) {
            await handleEdit(value, updateModalVisible);
          }

        }}
        onCancel={() => {
          handleDetailModalVisible(false);
        }}
        type={type}
        group={groupList}
        updateModalVisible={updateModalVisible}
      />
    </>
  );
};

export default connect(({login})=>{
  return {
     userType:login.type?login.type:1
  }
})(TableList);
